<?php
/**
 * WsService.php
 *
 * @copyright   2023 thingsworld.com.cn - All Rights Reserved
 * @link        http://thingsworld.com.cn/
 * @author      stiffer.chen <chenl@thingsworld.com.cn>
 * @created     2023-02-24 17:07:00
 * @modified    2023-02-24 17:07:00
 *
 */

namespace App\Services;

use App\Library\Logger;
use Carbon\Carbon;
use WebSocket\Client;

class WsService
{

    const TYPE_WORK_ORDER = 'work_order';
    const TYPE_EVENT = 'event';

    private $url = '127.0.0.1';
    private $port = 9502;
    private $client;

    private $logger;

    public function __construct($url = '', $port = '')
    {
        if (!$url) {
            $url = $this->url;
        }
        if (!$port) {
            $port = $this->port;
        }
        $wsUrl = "ws://{$url}:{$port}?type=pusher";
        $this->client = new Client($wsUrl);
        $this->logger = new Logger('ws_clients');
    }

    public function sendMessage(int $businessId, string $businessType, string $message)
    {
        $data = [
            'type' => $businessType,
            'id' => $businessId,
            'message' => $message,
            'date' => Carbon::now()->toDateTimeString()
        ];

        $this->logger->info("write date to ws");
        $this->logger->info($data);

        $this->client->text(json_encode($data));
    }
}